//
//  MyCollectionViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/26.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class MyCollectionViewController: BaseViewController {
    var currentNumber:NSInteger = 0
    var totalNumber:NSInteger = 0
    var currentPage:NSInteger = 1
    let length:NSInteger = 20
    var tableview:UITableView!
     var dataArray:[FavoriteObj]! = []
    override func viewDidLoad() {

        super.viewDidLoad()
        self.title = "我的收藏"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        self.createTableView()
        // Do any additional setup after loading the view.
        if let session = GlobalDataHelper.instance.session{
            self.queryFavoriteList(session,offset: self.currentPage, length: self.length)
        }
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }

    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        tableview = UITableView(frame: CGRectMake(0, 64, view.bounds.size.width, view.bounds.size.height-64), style: UITableViewStyle.Plain)
        tableview.backgroundColor = UIColor.clearColor();
        tableview.separatorStyle = UITableViewCellSeparatorStyle.None
        tableview.showsHorizontalScrollIndicator = false
        tableview.showsVerticalScrollIndicator = false
        tableview.dataSource = self
        tableview.delegate = self
        let nib = UINib(nibName:"GoodsListCell", bundle:nil)
        tableview.registerNib(nib,forCellReuseIdentifier:"GoodsListCellID")
//        tableview.header =  MJRefreshNormalHeader(refreshingBlock:{[weak self] in
//            self?.currentNumber = 0
//            self?.currentPage = 1
//            self?.queryFavoriteList(GlobalDataHelper.instance.session,offset: self!.currentPage, length: self!.length)
//            }
//        )
        tableview.footer =  MJRefreshAutoNormalFooter(refreshingBlock:{[weak self] in
            self?.currentPage++
            self?.queryFavoriteList(GlobalDataHelper.instance.session,offset: self!.currentPage, length: self!.length)
            }
        )
        tableview.footer.hidden = true
        view.addSubview(tableview)
    }
    func queryFavoriteList(sessionid:String!,offset:Int,length:Int)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        parameters.setObject(NSNumber(integer: offset),forKey: "c")
        parameters.setObject(NSNumber(integer:length), forKey: "s")
        request.requestStart("/favorite/list", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if (dic?["result"])! as! String == "0"{
                    if let array = dic?.pareseDataToFavoriteArray(){
                        let total:NSString = dic?["data"]?["itemcount"] as! NSString
                        self.totalNumber = total.integerValue
                        if self.currentNumber == 0{
                            self.dataArray.removeAll(keepCapacity: false)
                            self.dataArray = array
                        }
                        else{
                            for i in 0..<array.count{
                                let obj:FavoriteObj = array[i]
                                self.dataArray.append(obj)
                            }
                        }
                        self.currentNumber = self.dataArray.count
                    }
                    dispatch_async(dispatch_get_main_queue()){
                        //添加成功处理
                        self.tableview.reloadData()
                        if self.currentNumber == self.totalNumber{
                            self.tableview.footer.noticeNoMoreData()
                        }
                        else{
                            self.tableview.footer.resetNoMoreData()
                        }
                        if self.tableview.contentSize.height<self.tableview.bounds.size.height{
                            self.tableview.footer.hidden = true
                        }
                        else{
                            self.tableview.footer.hidden = false
                        }
                    }
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    self.showTips("加载失败")
                    if self.currentNumber == self.totalNumber{
                        self.tableview.footer.noticeNoMoreData()
                    }
                    else{
                        self.tableview.footer.resetNoMoreData()
                    }
                    if self.tableview.contentSize.height<self.tableview.bounds.size.height{
                        self.tableview.footer.hidden = true
                    }
                    else{
                        self.tableview.footer.hidden = false
                    }
                }
            }
        })
        self.showProcess("加载中...")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension MyCollectionViewController:UITableViewDataSource,UITableViewDelegate{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
         return dataArray.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("GoodsListCellID", forIndexPath: indexPath) as! GoodsListCell
        let obj:FavoriteObj? = dataArray[indexPath.row]
        cell.goodsImageView.setImageWithUrl(obj!.image!,defaultImage: nil)
        cell.indexPath = indexPath
        cell.nameLbl.text = obj?.name
        cell.priceLbl.text = "¥"+obj!.price!
        cell.loveBtn.hidden = false
        cell.btnHandle = {[weak self] path in
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
            parameters.setObject(obj!.id!, forKey: "id")
            request.requestStart("/favorite/delete", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self?.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
                            self?.showTips("删除成功")
                            self?.dataArray.removeAtIndex(path!.row)
                            self?.tableview.reloadData()
                        }
                    }
                    
                }
                else{
                    dispatch_async(dispatch_get_main_queue()){
                        self?.showTips("删除失败")
                    }
                    
                }
            })
            self?.showProcess("处理中...")

        }
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 100
    }
 }
extension MyCollectionViewController:UIAlertViewDelegate{
    //    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){
    //        if buttonIndex == 0{
    //            return
    //        }
    //        var arequested = SoapRequestHelper()
    //        arequested.requestStart("cancelOrder", parameters: [("orderId",self.currentOrderId),("md5","1111")],compeleteHandle: {(data, response, error) -> Void in
    //            if error==nil{
    //                self.hiddenProcessView()
    //                let xmlHelper = XMLParseHelper(data: data,matchElement:"cancelOrderReturn",compeleteHandle:{responObj in
    //                    if let dic = responObj as? NSDictionary{
    //                        if (dic["result"] as! String) == "0"{
    //                            dispatch_async(dispatch_get_main_queue(), {[weak self] in
    //                                self?.showTips("操作成功")
    //                                self?.testSoap()
    //                            })
    //                        }
    //                        else{
    //                            dispatch_async(dispatch_get_main_queue(), {[weak self] in
    //                                self?.showTips("取消失败")
    //                                })
    //                        }
    //                    }
    //                })
    //            }
    //            else{
    //                dispatch_async(dispatch_get_main_queue(), {[weak self] in
    //                    self?.showTips("网络异常操作失败")
    //                    })
    //            }
    //
    //        })
    //        self.showProcess("正在处理")
    //    }
}